import React, { useState, useEffect } from 'react'
import { Space, Button, Table, Image, Popconfirm, message } from 'antd'
import { getBannerList, deleteBanner } from './../../api/banner'
import { useHistory } from 'react-router-dom'
import { formatArr, getMenu, checkPathName } from './../../utils/format'
import { connect } from 'react-redux'
import menus from '../../router/menus'
function Com({ checkedkeys, adminname }) {
  const [ bannerList, setBannerList ] = useState([])
  const history = useHistory()
  useEffect(() => {
    getBannerList().then(res => {
      setBannerList(res.data.data)
    })
  }, [])

  const columns = [
    {
      title: '序号',
      render (text, record, index) {
        return <span>{ index + 1 }</span>
      }
    },
    {
      title: '图片',
      dataIndex: 'img',
      render (text) {
        return <Image src = { text } style = {{ height: 60 }}></Image>
      }
    },
    {
      title: '链接',
      dataIndex: 'link'
    },
    {
      title: '提示',
      dataIndex: 'alt'
    },
    {
      title: '操作',
      render (text, record) {
        return (
          <Space>
            <Popconfirm
              title="确定删除吗?"
              onConfirm={ () => {
                deleteBanner({ bannerid: record.bannerid }).then(() => {
                  getBannerList().then(res => {
                    setBannerList(res.data.data)
                  })
                })
              }}
              onCancel={() => {}}
              okText="确定"
              cancelText="取消"
            >
              <Button>删除</Button>
            </Popconfirm>
          </Space>
        )
      }
    }
  ]
  const newCheckedkeys = formatArr(checkedkeys)

  const myMenu = adminname === 'admin' ? menus : getMenu(menus, newCheckedkeys)
  const flag = checkPathName(myMenu, '/banner/add', [])
  console.log('flag111', flag)
  return (
    <Space style={{ width: '100%' }} direction="vertical">
      <Button type="primary" onClick = { () => {
        flag ? history.push('/banner/add') : message.warning('暂无权限')
      }}>添加轮播图</Button>
      <Table 
        dataSource = { bannerList } 
        columns = { columns }
        rowKey = "bannerid" // rowKey = {(record) => record.bannerid}
      ></Table>
    </Space>
  )
}
export default connect(state => ({
  checkedkeys: state.getIn(['user', 'checkedkeys']),
  adminname: state.getIn(['user', 'adminname'])
}))(Com)

